package com.liuceng.zen.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.liuceng.zen.pojo.domain.BaseDomain;
import com.liuceng.zen.pojo.domain.GdtCreative;
import com.liuceng.zen.pojo.form.CampaignForm;
import com.liuceng.zen.pojo.form.DiyFormFrom;
import com.liuceng.zen.service.DashboardService;
import com.liuceng.zen.service.GdtCreativeService;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


@Controller
public class AjaxController extends BaseController {
  private final static Logger LOG = LoggerFactory.getLogger(AjaxController.class);
  @Autowired
  DashboardService dashboardService;
  @Autowired
  GdtCreativeService gdtCreativeService;

  // 广告和计划---广告计划---广告计划列表---广告计划详情---动态获取(渲染图表)
  @RequestMapping(value = "/ajax/sitetype/detail/{id}", method = RequestMethod.GET)
  public String detailData(@ModelAttribute("form") CampaignForm form, @PathVariable Integer id,
      HttpServletRequest req) {
    // 今天、 昨天、过去七天、过去三十天，,自定义,ajax请求获取数据
    final String TODAY = "1";
    final String YESTERDAY = "2";
    final String LAST_7_DAYS = "3";
    final String LAST_30_DAYS = "4";
    final String USER_DEFINED="5";

    String timeType =
        req.getParameter("timeType") == null ? LAST_7_DAYS : req.getParameter("timeType").toString();

    String start = req.getParameter("start");
    String end = req.getParameter("end");

    // 时间
   /* Date endDate = new Date();
    Date startDate = endDate;
    // 根据时间格式判断是哪个选择
    switch (timeType) {
      case YESTERDAY:
        startDate = DateUtils.addDays(endDate, -1);
        break;
      case LAST_7_DAYS:
        startDate = DateUtils.addDays(endDate, -6);
        break;
      case LAST_30_DAYS:
        startDate = DateUtils.addDays(endDate, -29);
        break;
      case TODAY:
      default:
        startDate = endDate;
    }*/
    // 查询条件
    Map<String, Object> params = new HashMap<>();
    // params.put("startDate", DateFormatUtils.format(startDate, "yyyy-MM-dd"));
    // params.put("endDate", DateFormatUtils.format(endDate, "yyyy-MM-dd"));
    params.put("startDate", start);
    params.put("endDate", end);
    params.put("memberId", getCurrentUserId());
    params.put("frontCampaignId", id);
    params.put("auditType", BaseDomain.AUDIT_PASS);
    // 获得总花费，总曝光量，总点击量
    Map<String, Object> totalData = dashboardService.findTotalData(params);
    // 按天分隔，获取每天的总花费，总曝光量，总点击量
    List<Map<String, Object>> data = new ArrayList<>();
    if(start.equals(end)&& getUserContext().getMember().getOperationType()==2){
      data = dashboardService.findRptHourList(params);
    }else{
      data = dashboardService.findDataList(params,start,end);
    }
    // 批量处理点击率
    data = data.stream().map(d -> {
      d.put("ctr",
          d.get("pv") == null || 0 == Integer.parseInt(d.get("pv").toString()) ? new BigDecimal(0)
              : new BigDecimal(100.0 * Integer.parseInt(d.get("pc").toString())
                  / Integer.parseInt(d.get("pv").toString())));
      d.put("total_cost",d.get("total_cost")==null?new BigDecimal(0) :((BigDecimal)d.get("total_cost")).divide(new BigDecimal(1), 2, RoundingMode.HALF_DOWN));
      return d;
    }).collect(Collectors.toList());
    //
    form.setTotalData(totalData);
    form.setDataList(data);
    form.setData(data.stream().map(d -> {
      return JSONArray.toJSON(d);
    }).collect(Collectors.toList()));
    form.setTimeSelect(timeType);
    form.setStart(start);
    form.setEnd(end);
    //
    return "campaign/_detail";
  }

  @RequestMapping(value = "/ajax/image", method = RequestMethod.GET)
  public @ResponseBody List<GdtCreative> getImage(HttpServletRequest req) {
    Long aid = Long.parseLong(req.getParameter("aid"));
    Integer crtSize = Integer.parseInt(req.getParameter("crtSize"));
    Map<String, Object> map = new HashMap<>();
    map.put("aid", aid);
    map.put("crtSize", crtSize);
    return gdtCreativeService.findByAid(map);
  }

  @RequestMapping(value = "/ajax/add/ladding_page", method = RequestMethod.GET)
  public String checkLaddingPage(@ModelAttribute("form") DiyFormFrom diy) {

    return "ad/laddingPage";
  }
}
